package com.geng.io.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;


public class NettyServer {
    private static NettyServer nettyServer = new NettyServer();

    private EventLoopGroup bossGroup;
    private EventLoopGroup workGroup;

    public static void main(String[] args) {
        NettyServer nettyServer = NettyServer.singleton();
        nettyServer.start(9999);
    }

    public void start(final int port){
        synchronized (NettyServer.class){
            if(bossGroup != null || workGroup != null) return;
            bossGroup = new NioEventLoopGroup();
            workGroup = new NioEventLoopGroup();
            try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap
                    .group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,1024)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new EchoHandler());
                        }
                    });

                ChannelFuture f = serverBootstrap.bind(port).sync();
                f.channel().closeFuture().sync();
            }catch (InterruptedException e){
                throw new RuntimeException(e);
            }finally {
                bossGroup.shutdownGracefully();
                workGroup.shutdownGracefully();
            }
        }
    }

    private NettyServer(){}

    public  static NettyServer singleton(){
        return nettyServer;
    }
}
